//
//  UIButton+SMSVerificationCode.swift
//  FM
//
//  Created by x on 2017/11/23.
//  Copyright © 2017年 HLB. All rights reserved.
//

import UIKit

extension UIButton {
    
    
    /// 添加一个定时器方法
    ///
    /// - Parameter time: <#time description#>
    func getSMSVerificationCode(time:Int, backgroundColor:UIColor) -> Void {
        
        self.isEnabled = false
        self.backgroundColor = UIColor.lightGray
        self.titleLabel?.font = UIFont.systemFont(ofSize: 12)
        var countTime = time
        
        //1.创建一个GCD定时器
        let timer = DispatchSource.makeTimerSource(flags: DispatchSource.TimerFlags.init(rawValue: 0), queue: DispatchQueue.global())
        
        //2.设置定时器的启动时间 (现在开始启动  1秒钟执行一次)
        timer.scheduleRepeating(deadline: DispatchTime.now(), interval: DispatchTimeInterval.seconds(1))
        
        //3.设置GCD定时器的处理事情
        timer.setEventHandler { 
            //3.1处理按钮发生的事情
            countTime -= 1
            
            //3.2判断时间有没有走完
            if countTime <= 0 {
                timer.cancel()
                DispatchQueue.main.async {
                    self.isEnabled = true
                    self.setTitle("获取验证码", for: UIControlState.normal)
                    self.backgroundColor = backgroundColor
                }
            }else {
                DispatchQueue.main.async {
                    //设置按钮的标题
                    let title = String.init(format: "%d秒后再次获取", countTime)
                    self.setTitle(title, for: UIControlState.normal)
                }
            }
        }
        
        //4.启动GCD定时器
        timer.activate()
    }
}
